import { useEffect, useState } from "react";
import { Button, Card, Form, Input, Modal, Space, Table, message } from "antd";
import { DeleteOutlined, EditOutlined, PlusOutlined } from "@ant-design/icons";
import { ColumnsType } from "antd/es/table";
import { commonService } from "@/api/services/commonService";
import dayjs from "dayjs";

interface CategoryItem {
	id: number;
	name: string;
	createtime: number;
	updatetime: number;
	sort: number;
	status: string;
}

const CategoryPage = () => {
	const [form] = Form.useForm();
	const [categoryList, setCategoryList] = useState<CategoryItem[]>([]);
	const [loading, setLoading] = useState(false);
	const [modalVisible, setModalVisible] = useState(false);
	const [editingId, setEditingId] = useState<number | null>(null);

	const loadData = async () => {
		try {
			setLoading(true);
			const data = await commonService.getCategoryList();
			setCategoryList(data);
		} catch (error) {
			message.error("加载失败");
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		loadData();
	}, []);

	const handleAdd = () => {
		form.resetFields();
		setEditingId(null);
		setModalVisible(true);
	};

	const handleEdit = (record: CategoryItem) => {
		form.setFieldsValue(record);
		setEditingId(record.id);
		setModalVisible(true);
	};

	const handleDelete = async (id: number) => {
		try {
			await commonService.deleteCategory(id);
			message.success("删除成功");
			loadData();
		} catch (error) {
			message.error("删除失败");
		}
	};

	const handleOk = async () => {
		try {
			const values = await form.validateFields();
			if (editingId) {
				await commonService.editCategory({ ...values, id: editingId });
				message.success("编辑成功");
			} else {
				await commonService.addCategory(values);
				message.success("添加成功");
			}
			setModalVisible(false);
			loadData();
		} catch (error) {
			message.error(editingId ? "编辑失败" : "添加失败");
		}
	};

	const columns: ColumnsType<CategoryItem> = [
		{
			title: "分类名称",
			dataIndex: "name",
			key: "name",
		},
		{
			title: "排序",
			dataIndex: "sort",
			key: "sort",
		},
		{
			title: "创建时间",
			dataIndex: "createtime",
			key: "createtime",
			render: (time) => dayjs.unix(time).format("YYYY-MM-DD HH:mm:ss"),
		},
		{
			title: "更新时间",
			dataIndex: "updatetime",
			key: "updatetime",
			render: (time) => dayjs.unix(time).format("YYYY-MM-DD HH:mm:ss"),
		},
		{
			title: "操作",
			key: "action",
			render: (_, record) => (
				<Space size="middle">
					<Button
						type="link"
						icon={<EditOutlined />}
						onClick={() => handleEdit(record)}
					>
						编辑
					</Button>
					<Button
						type="link"
						danger
						icon={<DeleteOutlined />}
						onClick={() => handleDelete(record.id)}
					>
						删除
					</Button>
				</Space>
			),
		},
	];

	return (
		<div>
			<Card>
				<Space style={{ marginBottom: 16 }}>
					<Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
						添加分类
					</Button>
				</Space>

				<Table
					columns={columns}
					dataSource={categoryList}
					loading={loading}
					rowKey="id"
				/>
			</Card>

			<Modal
				title={editingId ? "编辑分类" : "添加分类"}
				open={modalVisible}
				onOk={handleOk}
				onCancel={() => setModalVisible(false)}
			>
				<Form form={form}>
					<Form.Item
						name="name"
						label="分类名称"
						rules={[{ required: true, message: "请输入分类名称" }]}
					>
						<Input placeholder="请输入分类名称" />
					</Form.Item>
					<Form.Item name="sort" label="排序">
						<Input type="number" placeholder="请输入排序" />
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
};

export default CategoryPage;
